﻿$(document).ready(function () {

    // defint tab containers
    var tabContainers = $('div.tabs > div');

    $('div.tabs ul.tabNavigation a').click(function () {
        tabContainers.hide().filter(this.hash).show();

        $('div.tabs ul.tabNavigation li').removeClass('selected');
        $(this).parent().addClass('selected');

        return false;
    }).filter(':first').click();

    // hide #back-top first
    $(".back-top").hide();

    // fade in #back-top
    $(function () {
        $(window).scroll(function () {
            if ($(this).scrollTop() > 100) {
                $('.back-top').fadeIn();
            } else {
                $('.back-top').fadeOut();
            }

            var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

            if (scrollBottom > 100) {
                $('.go-bottom').fadeIn();
            } else {
                $('.go-bottom').fadeOut();
            }
        });

        // scroll body to 0px on click
        $('.go-bottom a').click(function () {
            $('body,html').animate({
                scrollTop: 20000
            }, 800);
            return false;
        });

        $('.back-top a').click(function () {
            $('body,html').animate({
                scrollTop: 0
            }, 800);
            return false;
        });
    });

    // format
    $(".datepicker").datepicker({
        constrainInput: true,
        onSelect: function () { $(".ui-datepicker a").removeAttr("href"); }
    });

    $('input.auto').autoNumeric({ aSep: ',', aDec: '.', aPad: false, vMin: '-999999999.99' });
    $('input.auto').focus(function () { if (this.value == '0') this.value = ''; });
    $('input.auto').blur(function () { if (this.value == '') this.value = '0'; });

    $('input.integer').autoNumeric({ aSep: ',', aDec: '.', aPad: false, vMin: '-999999999.99' });
    $('input.integer').focus(function () { if (this.value == '0') this.value = ''; });
    $('input.integer').blur(function () { if (this.value == '') this.value = '0'; });

});

$.fn.sumValues = function () {
    var sum = 0;
    this.each(function () {
        if ($(this).is(':input') || $(this).is(':select')) {
            var val = $(this).val();
        }
        sum += toFloat("" + val);
    });
    return sum;
};

/// <summary>
/// Sum the price multiple the num of pax equals the cruise package.
/// </summary>
$.fn.sumCruisePackage = function () {
    var sum = 0;
    this.each(function () {
        var index = $(this).attr("index");
        var unitPrice = $(this).val();
        var numOfPax = $(".numberclient-" + index).val();

        sum += toFloat("" + unitPrice) * parseInt(numOfPax);
    });
    return sum;
};

function stringformat(str) {
    for (i = 0; i < arguments.length; i++) {
        str = replaceAll(str, '{' + i + '}', arguments[i + 1]);
    }
    return str;
}

function replaceAll(source, stringToFind, stringToReplace) {
    var temp = source;
    var index = temp.indexOf(stringToFind);
    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }

    return temp;

}

function checkBooking(bookingCode, reservationId) {
    var result = false;
    var params = "{ 'bookingCode': '" + bookingCode + "', 'reservationId': '" + reservationId + "' }";
    $.ajax({
        type: "POST",
        url: "/Get.asmx/CheckBookingCode",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: params,
        async: false,
        success: function (data) {
            result = data.d;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var err = eval("(" + XMLHttpRequest.responseText + ")");
            alert(err.Message);
        }
    });
    return result;
}

function getRate(code, date) {
    var rate;
    if (date == null) date = new Date();
    $.ajax({
        type: "POST",
        url: "/Get.asmx/GetExchange",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{ code: '" + code + "', date: '" + date + "' }",
        async: false,
        success: function (data) {
            rate = data.d;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var err = eval("(" + XMLHttpRequest.responseText + ")");
            alert(err.Message);
        }
    });
    return rate;
}

function getCash(code) {
    var rate;
    $.ajax({
        type: "POST",
        url: "/Get.asmx/GetCash",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{ code: '" + code + "' }",
        async: false,
        success: function (data) {
            rate = data.d;
        },
        error: function () {
            alert("error");
        }
    });
    return rate;
}

function submitExtra(state) {
    var template = '<tr id="{0}" {1}><td><label class="label label_{0}">{2}</label>' +
                    '<input class="input edit_{0} datepicker" style="display: none" value="{2}" disabled="disabled" /></td>' +
                    '<td><label class="label label_{0}">{3}</label>' +
                    '<input class="input edit_{0}" style="display: none" value="{3}" /></td>' +
                    '<td style="text-align: right"><label class="label label_{0}">{4}</label>' +
                    '<input class="input edit_{0} auto extraAmount" style="display: none" value="{4}" /></td>' +
                    '<td style="text-align: center"><label class="label label_{0}"></label>' +
                    '<input type="checkbox" class="input edit_{0} checkbox" style="display: none" /></td>' +
                    '<td><a extraid="{1}" class="btnDelete">Remove</a></td></tr>';

    switch (state) {
        case 'add':
            $.ajax({
                url: "/Update.asmx/InsertExtraService",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                async: false,
                success: function (data) {
                    extra = data.d;
                    var tbody = $('#gridExtraService > tbody');
                    var seq = ($('tr', tbody).length + 1);
                    var evenClass = (seq % 2 == 0 ? ' class="evenRow"' : '');
                    var row = stringformat(template, extra.ExtraID, evenClass, formatJSONDate(extra.ExtraDate), extra.Description, extra.Amount);

                    if ($.trim(tbody.html()) == '') {
                        tbody.html(row);
                    }
                    else {
                        // Insert
                        $('tr:last', tbody).after(row);
                    }

                    $('tr:last', tbody).click(function () {
                        var id = $(this).attr('id');
                        $(".label_" + id).hide();
                        $(".edit_" + id).show();
                        $(this).addClass("highlight");
                    }).change(function () {
                        var id = $(this).attr('id');
                        $(this).children('td').each(function () {
                            if ($(this).children('.input').attr('type') == 'checkbox') {
                                var trTag = $(this).closest('tr');

                                if ($(this).children('.input').is(':checked')) {
                                    $(this).children('label').text('Yes');

                                    trTag.children("td:eq(2)").children("input").addClass("shuttle");
                                    trTag.children("td:eq(2)").children("input").removeClass("extraAmount");
                                }
                                else {
                                    $(this).children('label').text('');

                                    trTag.children("td:eq(2)").children("input").addClass("extraAmount");
                                    trTag.children("td:eq(2)").children("input").removeClass("shuttle");
                                }
                            }
                            else {
                                var value = $(this).children('.input').val();
                                $(this).children('label').text(value);
                            }
                        });
                    });

                    $('tr:last', tbody).children("td:eq(4)").children("a").click(function () {
                        if (confirm('Are you sure you want to delete this extra service?')) {
                            $(this).closest('tr').remove();
                            getTotal();
                        }
                    });

                    $('tr:last', tbody).children('td').each(function () {
                        $(this).children('.auto').autoNumeric({ aSep: ',', aDec: '.', aPad: false, vMin: '-999999999.99' })
                        .focus(function () { if (this.value == '0') this.value = ''; })
                        .blur(function () { if (this.value == '') this.value = '0'; });

                        $(this).children('.datepicker').datepicker({
                            constrainInput: true,
                            onSelect: function () {
                                var tdTag = $(this).closest('td');
                                tdTag.children('label').text(this.value);
                                $(".ui-datepicker a").removeAttr("href");
                            }
                        });

                        $(this).children('.input').mouseup(function () {
                            return false;
                        });
                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    var err = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(err.Message);
                }
            });
            break;
        case 'delete':
            break;
    }
}

/// <summary>
/// Get the reservation detail
/// </summary>
function getReservationDetails(reservation) {
    reservation.ReservationDetails = [];
    $('.ddlStatus').each(function (index) {
        var item = {
            CabinStatus: parseInt($(this).val()),
            BlockDates: parseInt($(".blockdate-" + index + " option:selected").val()),
            CabinID: parseInt($(".cabinid-" + index).val()),
            Representative: $(".representative-" + index).val(),
            NumOfPeople: parseInt($(".numberclient-" + index + " option:selected").val()),
            Status: parseInt($(".typeofcabin-" + index).val()),
            UnitPrice: toFloat($(".cabinprice-" + index).val()),
            Note: $(".notedetail-" + index).val()
        };
        reservation.ReservationDetails.push(item);
    });
}

function getReservationExtras(reservation) {
    reservation.ReservationExtras = [];
    $("table#gridExtraService > tbody > tr").each(function () {

        var isShuttle = $.trim($(this).children("td:eq(3)").children("label").text()) == 'Yes';

        // Some info need to save.
        var extra = {
            ExtraID: $(this).attr('id'),
            ExtraDate: $.trim($(this).children("td:eq(0)").children("label").text()),
            Description: $.trim($(this).children("td:eq(1)").children("label").text()),
            Amount: toFloat($(this).children("td:eq(2)").children("label").text()),
            IsShuttle: isShuttle
        };
        reservation.ReservationExtras.push(extra);
    });
}